package com.study.ceph.web;

import com.amazonaws.services.s3.AmazonS3;
import com.study.ceph.config.CephConfig;
import com.study.ceph.connection.CephConnectionPool;
import com.study.ceph.connection.CephUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
public class CephController {

    @Autowired
    private CephConfig cephConfig;

    @Autowired
    private CephConnectionPool cephConnectionPool;

    @GetMapping("/upfile/{fileName}")
    public Object upfile(@PathVariable("fileName") String fileName) {
        AmazonS3 connection = cephConnectionPool.getConnection();
        try {
            String basePath = "/Users/zhangbo/Downloads/临时文件/" + fileName;
            boolean upload = CephUtil.upload(connection, cephConfig.getBucketName(), "/temp/"+ UUID.randomUUID().toString().replaceAll("-","") + "/" + fileName, getFileBytes(new File(basePath)));
            return upload;
        } catch (Exception e) {
            log.error("文件上传异常：{}", e);
        } finally {
            cephConnectionPool.returnConnection(connection);
        }
        return false;
    }

    @GetMapping("/download/{fileName}")
    public Object download(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        AmazonS3 connection = cephConnectionPool.getConnection();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            String basePath = "/temp/" + fileName;
            String downLoadName = CephUtil.download(connection, cephConfig.getBucketName(), basePath, outputStream);
            log.info("文件下载名称：{}", downLoadName);
        } catch (Exception e) {
            log.error("文件下载异常：{}", e);
        } finally {
            cephConnectionPool.returnConnection(connection);
        }
        return "success";
    }


    public static byte[] getFileBytes(File file) {
        byte[] buffer = null;
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
            byte[] b = new byte[1024];
            int n = -1;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

}
